<template>
  <div class="app-container">
    <div class="recharge-notice">
      <div class="header">
        <h2>充值说明管理</h2>
        <el-button type="primary" @click="handleCreate">
          <i class="el-icon-plus"></i>
          添加说明
        </el-button>
      </div>
      
      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="noticeList"
        border
        fit
        highlight-current-row
        style="width: 100%;"
      >
        <el-table-column
          label="序号"
          prop="id"
          sortable
          align="center"
          width="80"
        />
        <el-table-column
          label="说明内容"
          prop="content"
          min-width="300"
          show-overflow-tooltip
        />
        <el-table-column
          label="操作"
          align="center"
          width="150"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleUpdate(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      :title="dialogStatus === 'create' ? '添加说明' : '编辑说明'"
      :visible.sync="dialogFormVisible"
      width="600px"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="100px"
        style="width: 100%;"
      >
        <el-form-item label="说明内容" prop="content">
          <el-input
            v-model="temp.content"
            type="textarea"
            :rows="4"
            placeholder="请输入说明内容"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { precautionListSave, precautionList ,precautionDelete  } from '../../../libs/api'

export default {
  name: 'TestAPP',
  data() {
    return {
      tableKey: 0,
      listLoading: false,
      noticeList: [],
      temp: {
        id: undefined,
        content: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      rules: {
        content: [{ required: true, message: '说明内容不能为空', trigger: 'blur' }]
      }
    }
  },
  methods: {
    // 获取列表数据
    async fetchNoticeList() {
      this.listLoading = true
      try {
        const response = await precautionList()
        this.noticeList = response.data || []
        console.log('获取充值说明列表', response)
      } catch (error) {
        console.error('获取充值说明失败:', error)
        this.$message({
          type: 'error',
          message: '获取数据失败'
        })
      } finally {
        this.listLoading = false
      }
    },
    
    // 添加
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    
    // 编辑
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    
    // 删除
    handleDelete(row) {
      this.$confirm('确定要删除这条说明吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 调用删除API，传递id参数
          await precautionDelete({
            id: row.id, // 删除时content可以为空或传递特殊标识
          })
          
          this.fetchNoticeList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        } catch (error) {
          console.error('删除失败:', error)
          this.$message({
            type: 'error',
            message: '删除失败'
          })
        }
      })
    },
    
    // 创建数据
    createData() {
      this.$refs['dataForm'].validate(async (valid) => {
        if (valid) {
          try {
            const tempData = Object.assign({}, this.temp)
            // 调用API保存数据
            const response = await precautionListSave({
              content: tempData.content,
              id: tempData.id || null // 新增时id为null
            })
            
            // 如果API返回了新的id，使用API返回的id
            if (response.data && response.data.id) {
              tempData.id = response.data.id
            } else {
              tempData.id = Date.now() // 临时ID
            }
            
            this.noticeList.unshift(tempData)
            this.dialogFormVisible = false
            this.$message({
              message: '创建成功',
              type: 'success'
            })
          } catch (error) {
            console.error('创建失败:', error)
            this.$message({
              type: 'error',
              message: '创建失败'
            })
          }
        }
      })
    },
    
    // 更新数据
    updateData() {
      this.$refs['dataForm'].validate(async (valid) => {
        if (valid) {
          try {
            const tempData = Object.assign({}, this.temp)
            // 调用API更新数据
            await precautionListSave({
              content: tempData.content,
              id: tempData.id
            })
            
           this.fetchNoticeList()
            this.dialogFormVisible = false
            this.$message({
              message: '更新成功',
              type: 'success'
            })
          } catch (error) {
            console.error('更新失败:', error)
            this.$message({
              type: 'error',
              message: '更新失败'
            })
          }
        }
      })
    },
    
    // 重置表单
    resetTemp() {
      this.temp = {
        id: undefined,
        content: ''
      }
    }
  },
  created() {
    // 组件创建时获取数据
    this.fetchNoticeList()
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.recharge-notice {
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      color: #303133;
      margin: 0;
      font-size: 24px;
      font-weight: 600;
    }
  }
}

.dialog-footer {
  text-align: right;
}

// 响应式设计
@media (max-width: 768px) {
  .app-container {
    padding: 10px;
  }
  
  .recharge-notice .header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
    
    h2 {
      font-size: 20px;
    }
  }
}
</style>

